<script setup lang="ts">
import { computed, reactive, shallowRef, watch } from 'vue';
import { $t } from '@/locales';
import {
  fetchGetCurrentUserRoleMenuButtons,
  fetchGetRoleSelectedMenuButtons,
  fetchSaveRoleMenuButtons
} from '@/service/api';

defineOptions({
  name: 'ButtonAuthModal'
});
interface Props {
  roleId: string;
}
const props = defineProps<Props>();
const checks = shallowRef<string[]>([]);
const buttonList = shallowRef<Api.SystemManage.RoleMenuButton[]>([]);
const title = computed(() => $t('common.edit') + $t('page.manage.role.buttonAuth'));
const visible = defineModel<boolean>('visible', {
  default: false
});
const model: Api.SystemManage.RoleMenuButtonPermission = reactive(createDefaultModel());
function createDefaultModel() {
  return {
    id: props.roleId,
    permissionIds: []
  };
}
function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  model.permissionIds = checks.value;
  const { error } = await fetchSaveRoleMenuButtons(model);
  if (!error) {
    window.$message?.success?.($t('common.modifySuccess'));
    closeModal();
  }
}

async function getRoleSelectedButtons() {
  const { error, data } = await fetchGetRoleSelectedMenuButtons(props.roleId);
  if (!error && data) {
    checks.value = data;
    await getPermissionData();
  }
}

async function getPermissionData() {
  const { error, data } = await fetchGetCurrentUserRoleMenuButtons();
  if (!error && data) {
    buttonList.value = data;
  }
}

watch(visible, () => {
  if (visible.value) {
    checks.value = [];
    Object.assign(model, createDefaultModel());
    getRoleSelectedButtons();
  }
});
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-720px">
    <NCheckboxGroup v-model:value="checks" class="max-h-500px overflow-auto" size="small">
      <NDescriptions label-placement="left" bordered :column="1">
        <NDescriptionsItem
          v-for="item in buttonList"
          :key="item.id"
          :label="item.i18nKey ? $t(item.i18nKey) : item.menuName"
        >
          <NGrid :y-gap="8" :cols="4">
            <NGridItem v-for="button in item.buttons" :key="button.code">
              <NCheckbox :label="button.desc" :value="button.code" />
            </NGridItem>
          </NGrid>
        </NDescriptionsItem>
      </NDescriptions>
    </NCheckboxGroup>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeModal">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
